import { Injectable } from "@nestjs/common";
import { TaskProgressStore } from "./task-progress.store";

@Injectable()
export class SseEnhanceService {
    constructor(private readonly taskProgressStore: TaskProgressStore) { }

    // Execute  async task and update progress
    executeTask(taskId: string): void {
        this.taskProgressStore.initTask(taskId);

        // Simulate async task
        const taskRunner = async () => {
            try {
                for (let i = 1; i <= 100; i++) {
                    this.taskProgressStore.updateProgress(taskId, i, `Working in...${i}%`);

                    // simulate time-consuming task
                    await new Promise(resolve => setTimeout(resolve, 100));
                }
            } catch (error) {
                this.taskProgressStore.markTaskFailed(taskId, `Task Failed: ${error.message}`);
            }
        };

        taskRunner();
    }

    // Check task exists
    isTaskExists(taskId: string): boolean {
        return this.taskProgressStore.getTask(taskId) !== null;
    }
}